import 'dart:io';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:wallpaper/components/AlertDialog/my_loading.dart';
import 'package:wallpaper/components/empty.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/pages/other/local_image_view.dart';

class GetAllImagesExample extends StatefulWidget {
  const GetAllImagesExample({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _GetAllImagesExampleState createState() => _GetAllImagesExampleState();
}

class _GetAllImagesExampleState extends State<GetAllImagesExample> {
  AssetPathEntity album = AssetPathEntity(id: '', name: '');
  List<String> imageList = [];
  int pageSize = 10; // 每页加载的图片数量
  int currentPage = 0; // 当前页码

  @override
  void initState() {
    super.initState();
    _requestPermissionAndLoadAlbums();
  }

  Future<void> _requestPermissionAndLoadAlbums() async {
    // 请求相册权限
    final authState = await PhotoManager.requestPermissionExtend();
    if (authState.isAuth) {
      // 获取所有相册
      final albumList = await PhotoManager.getAssetPathList();
      for (var i = 0; i < albumList.length; i++) {
        if (albumList[i].id == 'isAll' || albumList[i].name == 'Recent') {
          setState(() {
            album = albumList[i];
          });
          break;
        }
      }
    }
    _loadImages();
  }

  Future<void> _loadImages() async {
    // 清空之前的图片列表
    setState(() {
      imageList.clear();
      currentPage = 0; // 重置页码
    });

    // 分页加载图片
    while (true) {
      int start = currentPage * pageSize;
      int end = start + pageSize;

      // 获取当前页的图片
      final assets = await album.getAssetListRange(start: start, end: end);

      // 如果没有更多图片，退出循环
      if (assets.isEmpty) {
        break;
      }

      // 处理图片并添加到列表
      for (var asset in assets) {
        if (asset.type == AssetType.image) {
          final file = await asset.file;
          // final compressedFile = await _compressImage(file?.path ?? '');
          setState(() {
            imageList.add(file!.path);
          });
        }
      }

      currentPage++;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
        elevation: 0,
        title: Text(
          '本地相册',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        actions: [
          IconButton(onPressed: _loadImages, icon: const Icon(Icons.refresh))
        ],
      ),
      body: imageList.isEmpty
          ? Empty()
          : Padding(
              padding: const EdgeInsets.all(5),
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: OptionsBase().imageColumns(context),
                  childAspectRatio: 0.7,
                ),
                itemCount: imageList.length,
                itemBuilder: (context, index) {
                  return buildItem(context, index);
                },
              ),
            ),
    );
  }

  Widget buildItem(context, int index) {
    return Container(
      margin: EdgeInsets.all(OptionsBase().padding / 2),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Theme.of(context).colorScheme.shadow,
              offset: Offset(1, 2),
              blurRadius: 2,
            ),
          ]),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => LocalImageView(
                        images: imageList,
                        selectedIndex: index,
                      )),
            );
          },
          child: Stack(alignment: Alignment.bottomLeft, children: [
            SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: buildLoad(context, imageList[index])),
          ]),
        ),
      ),
    );
  }

  Widget buildLoad(BuildContext context, String imageUrl) {
    return ExtendedImage.file(
      File(imageUrl),
      width: double.infinity,
      height: double.infinity, // 屏幕高度
      fit: BoxFit.cover,
      mode: ExtendedImageMode.gesture,
      initGestureConfigHandler: (state) {
        return GestureConfig(
          // 缩放最小值
          minScale: 1,
          // 缩放动画最小值 当缩放结束时回到 minScale 值
          animationMinScale: 1,
          // 缩放最大值
          maxScale: 1,
          // 缩放动画最大值 当缩放结束时回到 maxScale 值
          animationMaxScale: 1,
          // 缩放拖拽速度
          speed: 1.0,
          // 拖拽惯性速度
          inertialSpeed: 100.0,
          initialScale: 1.0,
          // 是否使用 ExtendedImageGesturePageView 展示图片
          inPageView: false,
          // 当图片的初始化缩放大于 1.0 的时候，根据相对位置初始化图片
          initialAlignment: InitialAlignment.center,
        );
      },

      /// 加载状态回调
      loadStateChanged: (ExtendedImageState state) {
        switch (state.extendedImageLoadState) {
          /// 加载中
          case LoadState.loading:
            return MyLoading(
              type: 3,
              size: 30,
            );

          /// 加载成功
          case LoadState.completed:
            return state.completedWidget;

          /// 加载失败
          case LoadState.failed:
            // 自己写的加载失败的组件 并且把重试的回调传递过去
            return Center(
              child: Icon(
                Icons.perm_media,
                color: Theme.of(context).colorScheme.primaryContainer,
                size: 50,
              ),
            );
        }
      },
    );
  }

  @override
  void dispose() {
    // 清理资源
    imageList.clear();
    super.dispose();
  }
}
